<?php

namespace app\api\controller;

use app\api\model\RushOrderEntrust;
use app\api\model\UserCoupon;
use app\api\model\UserScore;
use app\api\model\UserScoreExchange;
use app\common\controller\Api;
use app\common\library\Tools;
use app\common\model\ScoreLog;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\Request;
use think\Validate;

/**
 * E-我的相关接口
 * @ApiWeigh    (97)
 */
class User extends Api {
	protected $noNeedLogin = ['scoreIntro'];
	protected $noNeedRight = ['*'];

	protected $goodsModel = null;
	protected $userModel = null;

	public function __construct( Request $request = null ) {
		parent::__construct( $request );

		$this->goodsModel = new Goods();
		$this->userModel  = new \app\admin\model\User();
	}

	/**
	 * 用户信息
	 *
	 * @ApiTitle    (用户信息)
	 * @ApiSummary  (用户信息展示)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiReturnParams   (name="id", type="integer", required=true, description="用户id")
	 * @ApiReturnParams   (name="nickname", type="string", required=true, description="昵称")
	 * @ApiReturnParams   (name="avatar", type="string", required=true, description="头像")
	 * @ApiReturnParams   (name="invitation_qr", type="string", required=true, description="该用户的唯一邀请二维码:埋参为用户id")
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 */
	public function user_information() {
		$data                  = $this->auth->getUserinfo();
		$data['avatar']        = cdnurl( $data['avatar'], true );
		$data['invitation_qr'] = $this->request->domain().$data['invitation_qr'];
		$this->success( '个人中心信息展示', $data );
	}

	/**
	 * 修改个人信息
	 *
	 * @ApiTitle    (修改个人信息)
	 * @ApiSummary  (修改登录用户的信息)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiParams   (name="nickname", type="string", required=true, description="昵称")
	 * @ApiParams   (name="avatar", type="string", required=true, description="头像")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码:0=失败,1=成功")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 */
	public function edit_userinfo() {
		//验证参数
		$rules    = [
			'nickname' => 'require',
			'avatar'   => 'require',
		];
		$message  = [
			'nickname.require' => '昵称不能为空',
			'avatar.require'   => '头像不能为空',
		];
		$param    = $this->request->param();
		$validate = new Validate( $rules, $message );
		if ( !$validate->check( $param ) ) {
			$this->error( $validate->getError() );
		}
		$userId   = $this->auth->id;
		//判断昵称是否已存在
        $has_nick = $this->userModel->where('nickname',$param['nickname'])->where('id','neq',$userId)->field('id')->find();
        $has_nick && $this->error('昵称已存在');
        //更新个人信息
		$this->userModel->where( 'id', $userId )->update( ['nickname' => $param['nickname'], 'avatar' => $param['avatar']] );
		$this->success('编辑成功');
	}

	/**
	 * 邀请海报
	 *
	 * @ApiTitle    (邀请海报)
	 * @ApiSummary  (获取用户邀请海报相关信息)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiReturnParams   (name="id", type="integer", required=true, description="用户id:用作邀请码号码")
	 * @ApiReturnParams   (name="nickname", type="string", required=true, description="昵称")
	 * @ApiReturnParams   (name="avatar", type="string", required=true, description="头像")
	 * @ApiReturnParams   (name="invitation_qr", type="string", required=true, description="该用户的唯一邀请二维码:埋参为用户id")
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 */
	public function invitation_poster() {
		$user_info               = $this->auth->getUserinfo();
		$return['id']            = $user_info['id'];
		$return['nickname']      = $user_info['nickname'];
		$return['avatar']        = $user_info['avatar'];
		$return['invitation_qr'] = $this->request->domain().$user_info['invitation_qr'];
		$this->success( '该用户邀请海报页面信息', $return );
	}

//    /**
//     * @ApiTitle    (我的首页)
//     * @ApiSummary  (我的首页)
//     * @ApiMethod (POST)
//     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
//     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//     * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//     * @ApiReturn   ({
//    "code":"状态码",
//    "msg": "提示消息",
//    "data":  {
//    "userInfo": {
//    "id": "用户ID",
//    "nickname": "昵称",
//    "mobile": "手机号",
//    "avatar": "头像",
//    "level": "等级",
//    "total_score": "累计积分",
//    "score": "剩余积分"
//    },
//    "coupon_num": "优惠券数量",
//    "voucher_num": "购物券数量",
//    "dfk": "待付款",
//    "dfh": "待发货",
//    "dsh": "待收货",
//    "ywc": "已完成",
//    "yth": "已退款",
//    "all": "全部订单"
//    }
//    })
//     */
//    public function index()
//    {
//        $data['userInfo']=$this->auth->getUserinfo();
//        $userId=$this->auth->id;
//        $data['coupon_num']=Db::name('user_coupon')->where(['user_id'=>$userId,'status'=>1])->count('id');
//        $data['voucher_num']=Db::name('user_voucher')->where(['user_id'=>$userId,'status'=>1])->count('id');
//        $data['dfk']=Db::name('shop_order')->where(['user_id'=>$userId,'order_status'=>1])->count('id');
//        $data['dfh']=Db::name('shop_order')->where(['user_id'=>$userId,'order_status'=>2])->count('id');
//        $data['dsh']=Db::name('shop_order')->where(['user_id'=>$userId,'order_status'=>3])->count('id');
//        $data['ywc']=Db::name('shop_order')->where(['user_id'=>$userId,'order_status'=>4])->count('id');
//        $data['yth']=Db::name('shop_order')->where(['user_id'=>$userId,'order_status'=>21,'refund_status'=>1])->count('id');
//        $data['all']=Db::name('shop_order')->where(['user_id'=>$userId])->count('id');
//        $this->success('', $data);
//    }

//    /**
//     * @ApiTitle    (我的积分)
//     * @ApiSummary  (我的积分)
//     * @ApiMethod (POST)
//     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
//     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//     * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//     * @ApiReturn   ({
//    "code":"状态码",
//    "msg": "提示消息",
//    "data": {}
//    })
//     */
//    public function myScore(){
//        $userInfo=$this->auth->getUserinfo();
//        $data['score']=$userInfo['score'];
//        $site=Config::get('site');
//        $data['score_rule']=$site['score_rule'];
//        $this->success('我的积分',$data);
//    }

//    /**
//     * @ApiTitle    (积分明细)
//     * @ApiSummary  (积分明细)
//     * @ApiMethod (POST)
//     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
//     * @ApiParams   (name="date", type="string", required=false, description="月份")
//     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//     * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//     * @ApiReturn   ({
//    "code":"状态码",
//    "msg": "提示消息",
//    "data": {}
//    })
//     */
//    public function getScoreDetail(){
//        $rules = [
//            'date' => 'dateFormat:Y-m',
//        ];
//        $message = [
//            'date.dateFormat' => '日期格式错误',
//        ];
//        $validate = new Validate($rules, $message);
//
//        $param = $this->request->param();
//        if (!$validate->check($param)) {
//            $this->error($validate->getError());
//        }
//
//        $userId=$this->auth->id;
//        $where=['user_id'=>$userId];
//        if(empty($param['date'])){
//            $param['date']=date('Y-m');
//        }
//        $startTime=strtotime($param['date']);
//        $endTime=strtotime('+1 month',$startTime)-1;
//        $where['createtime']=['between',[$startTime,$endTime]];
//        $model=new UserScore();
//        $data=$model->where($where)->paginate(10)->toArray();
//        $data['income']=$model->where($where)->where(['score'=>['gt',0]])->sum('score');
//        $data['expenditure']=$model->where($where)->where(['score'=>['lt',0]])->sum('score');
//        $data['date']=$param['date'];
//        $this->success('',$data);
//    }

	/**
	 * @ApiTitle    (我的优惠券)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 * @ApiParams   (name=status, type=integer, required=false, description="状态:1=可使用,2=已使用,3=已过期")
	 * @ApiParams   (name=page, type=integer, required=true, description="页码")
	 * @ApiReturn   ({
	"code":"状态码",
	"msg": "提示消息",
	"data": {
	"total": "总数量",
	"per_page": "每页数量",
	"current_page": "当前页",
	"last_page": "最后一页",
	"data": [{
	"id": "优惠券ID",
	"name": "优惠券",
	"price": "面值",
	"bottom_price": "最低使用金额",
	"status": "状态:0=待支付,1=可使用,2=已使用,3=已过期",
	"validity_time": "有效时间"
	}]
	}
	})
	 */
	public function getUserCoupon() {
		$userId = $this->auth->id;
		//检验过期优惠券
		$this->checkCoupon( $userId );
		$param = $this->request->param();
		$model = new UserCoupon();
		$where = ['user_id' => $userId];
		if ( !empty( $param['status'] ) ) {
			$rules    = [
				'status' => 'require|between:1,3',
			];
			$message  = [
				'status.require' => '状态不能为空',
				'status.between' => '状态错误',
			];
			$validate = new Validate( $rules, $message );
			if ( !$validate->check( $param ) ) {
				$this->error( $validate->getError() );
			}
			$where['status'] = $param['status'];
		}
		$data = $model->where( $where )->order( 'end_time', 'desc' )->paginate( 10 )->toArray();
		$this->success( '', $data );
	}

	/**
	 * @ApiTitle    (我的优惠券-清空失效)
	 * @ApiMethod   (GET)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 * @ApiReturn   ({
	"code":"状态码",
	"msg": "提示消息",
	"data": null
	})
	 */
	public function userCouponValidEmpty() {
		$userId = $this->auth->id;
		//检验过期优惠券
		$this->checkCoupon( $userId );
		//清空 使用过的 和 已过期的 
		UserCoupon::where( 'user_id', $userId )->where( 'status', 'neq', 1)->delete();
		$this->success( '清空失效成功' );
	}

	/**
	 * 检验过期优惠券
	 */
	private function checkCoupon( $user_id ) {
		UserCoupon::where( 'user_id', $user_id )
			->where( 'status', 1 )
			->where( 'end_time', '<', time() )
			->update( ['status' => 3] );
	}

	/**
	 * @ApiTitle    (积分中心)
	 * @ApiMethod   (GET)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 * @ApiReturn   ({
	"code": 1,
	"msg": "",
	"time": "1652347469",
	"data": {
	"score": 0, //可用积分
	"score_total": 0, //累计获得佣金
	"score_today": 0, //今日获得
	"score_sevenday": 0 //近7日获得
	}
	})
	 */
	public function scoreCenter() {
		$user_id = $this->auth->id;
		$data    = [
			'score'          => $this->auth->score,
			'score_total'    => ScoreLog::where( 'user_id', $user_id )->where( 'is_settled', '1' )->sum( 'score' ),
			'score_today'    => ScoreLog::where( 'user_id', $user_id )->where( 'is_settled', '1' )->whereTime( 'updatetime', 'today' )->sum( 'score' ),
			'score_sevenday' => ScoreLog::where( 'user_id', $user_id )->where( 'is_settled', '1' )->whereTime( 'updatetime', '-7 days' )->sum( 'score' )
		];
		$this->success( '', $data );
	}

    /**
     * @ApiTitle    (积分中心-说明)
     * @ApiMethod   (GET)
     * @ApiReturn   ({
        "code": 1,
        "msg": "积分说明",
        "time": "1652769319",
        "data": {
            "score_intro": "积分说明"
        }
    })
     */
    public function scoreIntro() {
        //积分说明
        $data['score_intro'] = Tools::set_img_style( config( 'site.score_intro' ) );
        $this->success( '积分说明', $data );
    }

	/**
	 * @ApiTitle    (积分中心-积分记录)
	 * @ApiMethod   (GET)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 * @ApiParams   (name=is_settled, type=integer, required=false, description="是否已结算:0=否,1=是")
	 * @ApiParams   (name=page, type=integer, required=false, description="分页")
	 * @ApiReturn   ({
	"code": 1,
	"msg": "成功",
	"time": "1652347813",
	"data": {
	"total": 1, //数据总数
	"per_page": 10,
	"current_page": 1,
	"last_page": 1,
	"data": [{ //列表
	"score": 100, //积分
	"rush_order_no": "", //抢购订单号
	"updatetime": "2022-05-12", //时间
	"avatar": "http://petsdemo.qiniu.brofirst.cn/uploads/20220512/FlXRSFO-aQSlDK2exenW0oHonu5f.png", //头像
	"nickname": "Xue" //昵称
	}]
	}
	})
	 */
	public function scoreLogList() {
		$is_settled = $this->request->param( 'is_settled' );
		$is_settled = $is_settled > 0 ? '1' : '0';
		$list       = ScoreLog::alias( 'a' )
			->join( 'user b', 'b.id = a.lower_user_id' )
			->where( 'a.user_id', $this->auth->id )
			->where( 'a.is_settled', $is_settled )
			->field( 'a.score,a.rush_order_no,a.updatetime,b.avatar,b.nickname' )
            ->order('a.updatetime desc')
			->paginate( 10 )
			->each( function ( $v ) {
				$v['updatetime'] = date( 'Y-m-d', $v['updatetime'] );
				$v['avatar']     = cdnurl( $v['avatar'] );
			} );
		$this->success( '成功', $list );
	}

	/**
	 * @ApiTitle    (积分中心-申请兑换条件)
	 * @ApiMethod   (GET)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 * @ApiReturn   ({
	"code": 1,
	"msg": "",
	"time": "1652349851",
	"data": {
	"score": 0, //当前积分
	"score_exchange_limit": "10000" //兑换积分门槛
	}
	})
	 */
	public function scoreExchangeView() {
		$data = [
			'score'                => $this->auth->score,
			'score_exchange_limit' => config( 'site.score_exchange_limit' ),
		];
		$this->success( '', $data );
	}

	/**
	 * @ApiTitle    (积分中心-申请兑换)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 * @ApiParams   (name=score, type=integer, required=false, description="兑换积分")
	 * @ApiReturn   ({
	"code": 1,
	"msg": "",
	"time": "1652348302",
	"data": {
	"score": 0, //当前积分
	"score_exchange_limit": "10000" //兑换积分门槛
	}
	})
	 */
	public function scoreExchange() {
		$score                = $this->request->param( 'score' );
		$score_exchange_limit = config( 'site.score_exchange_limit' );
		$score < $score_exchange_limit && $this->error( '申请兑换积分不能少于' . $score_exchange_limit );
		$user = $this->auth->getUser();
		$score > $user['score'] && $this->error( '积分不足' );
		Db::startTrans();
		try {
			UserScoreExchange::create( [
				'user_id' => $this->auth->id,
				'score'   => $score,
				'before'  => $user['score'],
				'after'   => $user['score'] - $score,
			] );
			$user->setDec( 'score', $score );
			Db::commit();
		} catch ( PDOException $e ) {
			Db::rollback();
			$this->error( $e->getMessage() );
		} catch ( Exception $e ) {
			Db::rollback();
			$this->error( $e->getMessage() );
		}
		$this->success( '申请兑换成功' );
	}

	/**
	 * @ApiTitle    (积分中心-兑换记录)
	 * @ApiMethod   (GET)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 * @ApiParams   (name=page, type=integer, required=false, description="分页")
	 * @ApiReturn   ({
	"code": 1,
	"msg": "成功",
	"time": "1652348448",
	"data": {
	"total": 1, //数据总数
	"per_page": 10,
	"current_page": 1,
	"last_page": 1,
	"data": [{ //列表
	"score": 100, //申请兑换积分
	"status": "0", //审核状态:0=审核中,1=通过,2=拒绝
	"updatetime": "2022-05-12" //时间
	}]
	}
	})
	 */
	public function scoreExchangeList() {
		$list = UserScoreExchange::where( 'user_id', $this->auth->id )
			->field( 'score,status,updatetime' )
			->paginate( 10 )
			->each( function ( $v ) {
				$v['updatetime'] = date( 'Y-m-d', $v['updatetime'] );
			} );
		$this->success( '成功', $list );
	}

	/**
	 * @ApiTitle    (粉丝订单-统计)
	 * @ApiMethod   (GET)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 * @ApiParams   (name=page, type=integer, required=false, description="分页")
	 * @ApiReturn   ({
	"code": 1,
	"msg": "成功",
	"time": "1652348754",
	"data": {
	"order_price_total": 0, //订单总额
	"order_total": 0 //订单总数
	}
	})
	 */
	public function fansOrderTotal() {
		$order_price_total = ScoreLog::alias( 'a' )
			->join( 'rush_order b', 'b.id = a.rush_order_id' )
			->join( 'user seller', 'seller.id = b.seller_id' )
			->join( 'user buyer', 'buyer.id = b.buyer_id' )
			->where( 'a.user_id', $this->auth->id )
			->where( 'a.is_settled', '1' )
			->sum( 'b.goods_price' );
		$order_total       = ScoreLog::alias( 'a' )
			->join( 'rush_order b', 'b.id = a.rush_order_id' )
			->join( 'user seller', 'seller.id = b.seller_id' )
			->join( 'user buyer', 'buyer.id = b.buyer_id' )
			->where( 'a.user_id', $this->auth->id )
			->where( 'a.is_settled', '1' )
			->count();
		$this->success( '成功', compact( 'order_price_total', 'order_total' ) );
	}

	/**
	 * @ApiTitle    (粉丝订单-列表)
	 * @ApiMethod   (GET)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 * @ApiParams   (name=page, type=integer, required=false, description="分页")
	 * @ApiReturn   ({
	"code": 1,
	"msg": "成功",
	"time": "1652348834",
	"data": {
	"total": 1, //数据总数
	"per_page": 10,
	"current_page": 1,
	"last_page": 1,
	"data": [{ //列表
	"score": 100, //积分
	"order_no": "R2022050953531024", //订单编号
	"order_status": "4", //订单状态:2=待上架,3=已上架,4=已提货
	"goods_image": "http://petsdemo.qiniu.brofirst.cn/uploads/20220508/13cb1b8e54988cbb3710cc79897f0096.jpg", //商品图片
	"goods_name": "商品一", //商品名称
	"goods_no": "", //商品编号
	"goods_price": "7000.00", //商品价格
	"seller_nickname": "Xue", //归属人
	"buyer_nickname": "Xue" //购买人
	}]
	}
	})
	 */
	public function fansOrderList() {
		$list = ScoreLog::alias( 'a' )
			->join( 'rush_order b', 'b.id = a.rush_order_id' )
			->join( 'user seller', 'seller.id = b.seller_id' )
			->join( 'user buyer', 'buyer.id = b.buyer_id' )
			->where( 'a.user_id', $this->auth->id )
			->where( 'a.is_settled', '1' )
			->field( '
                a.score,
                b.order_no,b.order_status,b.goods_image,b.goods_name,b.goods_no,b.goods_price,
                seller.nickname seller_nickname,buyer.nickname buyer_nickname
            ' )
            ->order('a.updatetime desc')
			->paginate( 10 )
			->each( function ( $v ) {
				//格式化商品图片
				$v['goods_image'] = cdnurl( $v['goods_image'] );
			} );
		$this->success( '成功', $list );
	}

    /**
     * @ApiTitle    (收款管理)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652769625",
        "data": {
            "id": 1008,
            "bank_name": "他们", //所属银行
            "bank_card_no": "461646", //银行卡号
            "bank_card_holder": "请你", //银行卡持有人
            "url": "/u/1008"
        }
    })
     */
    public function myBankCard() {
        $user = \app\common\model\User::where('id',$this->auth->id)->field('id,bank_name,bank_card_no,bank_card_holder')->find();
        $this->success( '', $user );
    }

	/**
	 * @ApiTitle    (我的收益-统计)
	 * @ApiMethod   (GET)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 * @ApiReturn   ({
	"code": 1,
	"msg": "",
	"time": "1652349398",
	"data": {
	"profit_total": "0.00", //累计收益
	"profit_today": "0.00" //今日收益
	}
	})
	 */
	public function myRushProfitTotal() {
		$profit_total = number_format( RushOrderEntrust::alias( 'a' )
			->join( 'rush_order b', 'b.id = a.order_id' )
			->where( 'b.buyer_id', $this->auth->id )
			->where( 'a.pay_status', '1' )
			->sum( 'a.profit' ), 2 );
		$profit_today = number_format( RushOrderEntrust::alias( 'a' )
			->join( 'rush_order b', 'b.id = a.order_id' )
			->where( 'b.buyer_id', $this->auth->id )
			->where( 'a.pay_status', '1' )
			->whereTime( 'a.profit_time', 'today' )
			->sum( 'a.profit' ), 2 );
		$this->success( '', compact( 'profit_total', 'profit_today' ) );
	}

	/**
	 * @ApiTitle    (我的收益-列表)
	 * @ApiMethod   (GET)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 * @ApiParams   (name=page, type=integer, required=false, description="分页")
	 * @ApiReturn   ({
	"code": 1,
	"msg": "",
	"time": "1652349524",
	"data": {
	"total": 4, //数据总数
	"per_page": 10,
	"current_page": 1,
	"last_page": 1,
	"data": [{ //列表
	"profit": null, //收益
	"profit_rate": null, //收益率
	"order_no": "1", //订单号
	"profit_time": 2022-05-12, //收益时间
    "goods_name": "彷徨", //商品名称
	"goods_image": "http://petsdemo.qiniu.brofirst.cn/uploads/20220512/FlXRSFO-aQSlDK2exenW0oHonu5f.png" //商品图片
	}]
	}
	})
	 */
	public function myRushProfit() {
		$list = RushOrderEntrust::alias( 'a' )
			->join( 'rush_order b', 'b.id = a.order_id' )
			->where( 'b.buyer_id', $this->auth->id )
			->where( 'a.pay_status', '1' )
            ->where( 'a.profit_time', '>', 0 )
			->field( 'a.order_id,a.profit,a.profit_rate,a.profit_time,a.order_no,b.goods_name,b.goods_image' )
			->paginate( 10 )
			->each( function ( $v ) {
				$v['profit_time'] = date( 'Y-m-d H:i:s', $v['profit_time'] );
				$v['goods_image']   = cdnurl( $v['goods_image'] );
			} );
		$this->success( '', $list );
	}


	/**
	 * 我的粉丝
	 *
	 * @ApiTitle    (我的粉丝)
	 * @ApiSummary  (我的粉丝列表)
	 * @ApiMethod   (POST/GET)
	 *
	 * @ApiParams   (name="level", type="integer", required=true, description="粉丝等级:1=一级粉丝-默认一级,2=二级粉丝")
	 *
	 * @ApiReturnParams   (name="num", type="object", description="粉丝统计数据")
	 * @ApiReturnParams   (name="num.today_total", type="object", description="今日邀请")
	 * @ApiReturnParams   (name="num.not_today_total", type="object", description="历史邀请=非今日+今日")
	 * @ApiReturnParams   (name="total", type="object", description="粉丝总数")
	 * @ApiReturnParams   (name="total", type="object", description="粉丝总数")
	 * @ApiReturnParams   (name="per_page", type="object", description="每页数据")
	 * @ApiReturnParams   (name="current_page", type="object", description="当前页")
	 * @ApiReturnParams   (name="last_page", type="object", description="最后一页")
	 * @ApiReturnParams   (name="data", type="array", description="粉丝数据")
	 * @ApiReturnParams   (name="id", type="integer", description="用户id")
	 * @ApiReturnParams   (name="inviter_id", type="integer", description="邀请码id")
	 * @ApiReturnParams   (name="avatar", type="string", description="头像")
	 * @ApiReturnParams   (name="nickname", type="string", description="昵称")
	 * @ApiReturnParams   (name="createtime", type="string", description="加入时间")
	 */
	public function fans_list() {
		//验证参数
		$rules    = [
			'level' => 'in:1,2',
		];
		$message  = [
			'level.in' => '粉丝等级参数错误',
		];
		$param    = $this->request->param();
		$validate = new Validate( $rules, $message );
		if ( !$validate->check( $param ) ) {
			$this->error( $validate->getError() );
		}
		$userId = $this->auth->id;
		$level  = $param['level'];

		$field = 'id,inviter_id,avatar,nickname,createtime';
		//统计邀请数据
		$total = $this->userModel->getFansNum( $userId );

		if ( $level == '1' ) {
			$fan = $this->userModel->where( 'inviter_id', $userId )->field( $field )->paginate()->toArray();
		} else {
			$ids = $this->userModel->where( 'inviter_id', $userId )->column( 'id' );
			$where['inviter_id'] = $ids ? ['in', $ids] : -1;
			$fan = $this->userModel->field( $field )->where( $where )->paginate()->toArray();
		}

		$fan['num'] = $total;
		$this->success( '我的粉丝页面', $fan );
	}
}
